﻿using aier.dataaccess.dapper;
using aier.dataaccess.model;
using aier.xrm.wcf;
using log4net;
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace aier.business.logic
{
    public class RecommendBll
    {
        public RecommendDal recommendDal { get; set; }
        public ILog log { get; set; }

        public CommonWcf commonWcf { get; set; }

        public ChineseToLetterBll toLetterBll { get; set; }

        /// <summary>
        /// 查询推荐记录
        /// 查找条件：推荐记录ID
        /// 原程序 RecommendServiceImpl/qryRecommend
        /// </summary>
        /// <param name="recommendid"></param>
        /// <returns></returns>
        public RecommendView QueryRecommendById(Guid recommendid)
        {
            RecommendView recommendView = null;
            recommendView = recommendDal.QueryRecommendById(recommendid);
            return recommendView;
        }
        /// <summary>
        /// 查询推荐记录
        /// 查找条件：contactid,ownerid
        /// 原程序 RecommendServiceImpl/qryRecommendList
        /// </summary>
        /// <param name="contactid"></param>
        /// <param name="ownerid"></param>
        /// <returns></returns>
        public List<RecommendView> QueryRecommendList(Guid contactid, Guid ownerid)
        {
            List<RecommendView> recommendViews = null;
            recommendViews = recommendDal.QueryRecommendList(contactid, ownerid);
            return recommendViews;
        }

        /// <summary>
        /// 查询推荐记录
        /// 查找条件：startDateStr,endDateStr,istohospital,ownerid
        /// 原程序 RecommendServiceImpl/qryRecommendList
        /// </summary>
        /// <param name="startDateStr"></param>
        /// <param name="endDateStr"></param>
        /// <param name="istohospital">到院确认0、未到院；1、已到院</param>
        /// <param name="ownerid"></param>
        /// <returns></returns>
        public List<GroupResult<RecommendView>> QueryRecommendListByConditions(string startDateStr, string endDateStr, string hospital, Guid ownerid,Guid contactid,int state=0 ,bool?istohospital=null)
        {
            List<RecommendView> recommendViews = null;

            try
            {
                if (!string.IsNullOrWhiteSpace(startDateStr))
                {
                    startDateStr = DateTime.Parse(startDateStr).ToString("yyyy-MM-dd");
                }
                if (!string.IsNullOrWhiteSpace(endDateStr))
                {
                    endDateStr = DateTime.Parse(endDateStr).ToString("yyyy-MM-dd");
                }

                recommendViews = recommendDal.QueryRecommendListByConditions(startDateStr, endDateStr, hospital, ownerid, contactid, istohospital).GroupBy(p => new { p.new_recommendId }).Select(g => g.First()).ToList();
                if (state == 1)//已过期
                {
                    recommendViews = recommendViews.Where(t => t.new_appointmenttothehospitaldate < Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")) && t.new_istohospital == 0).ToList();
                }
                else if (state == 2)//3天内
                {
                    recommendViews = recommendViews.Where(t => t.new_appointmenttothehospitaldate.Value>= Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")) && t.new_appointmenttothehospitaldate.Value<= Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")).AddDays(3) && t.new_istohospital == 0).ToList();
                }
                else if (state == 3)//已完成
                {
                    recommendViews = recommendViews.Where(t => t.new_istohospital == 1).ToList();
                }
                List<GroupResult<RecommendView>> groupResults = GroupData(recommendViews);
                return groupResults;
            }
            catch (Exception ex)
            {
                log.Error("RecommendBll对象中，QueryRecommendListByConditions方法:"+ex.Message);
                return null;
            }

        }

        /// <summary>
        /// 对数据根据首字母分组
        /// </summary>
        /// <param name="recommendViews"></param>
        /// <returns></returns>
        private List<GroupResult<RecommendView>> GroupData(List<RecommendView> recommendViews)
        {
            var dicResult = recommendViews.Where(t => !string.IsNullOrWhiteSpace(t.new_leadName)).GroupBy(t => toLetterBll.startWithFirst(t.new_leadName[0])).ToDictionary(t => t.Key, t => t.ToList());
            var recommendViewsnull = recommendViews.Where(t => string.IsNullOrWhiteSpace(t.new_leadName));
            if (recommendViewsnull.ToList().Count > 0)
            {
                Dictionary<string, List<RecommendView>> dicResultnull = new Dictionary<string, List<RecommendView>>();
                dicResultnull.Add("#", recommendViewsnull.ToList());
                dicResult = dicResult.OrderBy(t => t.Key).Concat(dicResultnull).ToDictionary(k => k.Key, v => v.Value);
            }
            dicResult = dicResult.OrderBy(t => t.Key).ToDictionary(t => t.Key, t => t.Value);
            //List<GroupResult<RecommendView>> groupResults = new List<GroupResult<RecommendView>>();

            List<GroupResult<RecommendView>> groupResults = dicResult.ToList().Select(item =>
            {
                GroupResult<RecommendView> groupResult = new GroupResult<RecommendView>();
                groupResult.groupname = item.Key;
                groupResult.grouplist = item.Value;
                return groupResult;
            })?.ToList();
            return groupResults;
        }






        /// <summary>
        /// 增加推荐记录
        /// </summary>
        /// <param name="recommendModel"></param>
        /// <returns></returns>
        public ResResult AddRecommend(RecommendModel recommendModel)
        {
            ResResult resResult = new ResResult();
            try
            {
                Entity entity = recommendModel.AsCrmEntity();
                DoctorBll doctor = new DoctorBll();
                if (recommendModel.new_contact != Guid.Empty) {
                    ContactView contact = doctor.QryDoctorById((Guid)recommendModel.new_contact);
                    if (contact != null) {
                        if (contact.new_type == 3)
                        {//村医
                            entity["new_referraltype"] = new OptionSetValue(100000002);//村医转诊
                        }
                        else if (contact.new_type == 1)
                        {//外部
                            entity["new_referraltype"] = new OptionSetValue(100000001);//外部转诊          
                        }
                        else if (contact.new_type == 2) {//内部
                            entity["new_referraltype"] = new OptionSetValue(100000000);//内部转诊   
                        }
                    }
                }
                CompetitorBll competitor = new CompetitorBll();
                CompetitorView competitorView = competitor.QueryCompetitor((Guid)recommendModel.new_networkhospitalwherethehospital);
                if(competitorView!=null)
                    entity["new_ismedicalcouplet"] = (bool)competitorView.new_iscoopmedicalcouplet;
                
                
                Guid targetid = Guid.Empty;
                if (recommendModel.userid == Guid.Empty)
                {
                    targetid = commonWcf.CreateEntity(entity);
                }
                else
                {
                    targetid = commonWcf.CreateEntityProxy(recommendModel.userid, entity);

                }
                resResult = resResult.SuccessResult(targetid);
            }
            catch (Exception ex)
            {
                log.Error("RecommendBll对象中，AddRecommend方法:"+ex.StackTrace+ex.Message);
                resResult = resResult.FailResult(ex.Message);
            }
            return resResult;
        }
        /// <summary>
        /// 删除推荐记录
        /// </summary>
        /// <param name="recommendid"></param>
        /// <returns></returns>
        public ResResult DelRecommend(Guid recommendid)
        {
            ResResult resResult = new ResResult();
            try
            {
                commonWcf.DeleteEntityById("new_recommend", recommendid);
                resResult = resResult.SuccessResult() ;
            }
            catch (Exception ex)
            {
                log.Error("RecommendBll对象中，DelRecommend方法:" + ex.StackTrace + ex.Message);
                resResult = resResult.FailResult(ex.Message);
            }
            return resResult;
        }
        /// <summary>
        /// 修改推荐记录
        /// </summary>
        /// <param name="recommendModel"></param>
        /// <returns></returns>
        public ResResult UpdateRecommend(RecommendModel recommendModel)
        {
            ResResult resResult = new ResResult();
            try
            {
                if (recommendModel.new_recommendId==Guid.Empty)
                {
                    resResult = resResult.FailResult("new_recommendId不能为空");
                    return resResult;
                }
                Entity entity = recommendModel.AsCrmEntity();
                DoctorBll doctor = new DoctorBll();
                if (recommendModel.new_contact != Guid.Empty)
                {
                    ContactView contact = doctor.QryDoctorById((Guid)recommendModel.new_contact);
                    if (contact != null)
                    {
                        if (contact.new_type == 3)
                        {//村医
                            entity["new_referraltype"] = new OptionSetValue(100000002);//村医转诊
                        }
                        else if (contact.new_type == 1)
                        {//外部
                            entity["new_referraltype"] = new OptionSetValue(100000001);//外部转诊          
                        }
                        else if (contact.new_type == 2)
                        {//内部
                            entity["new_referraltype"] = new OptionSetValue(100000000);//内部转诊   
                        }
                    }
                }
                CompetitorBll competitor = new CompetitorBll();
                CompetitorView competitorView = competitor.QueryCompetitor((Guid)recommendModel.new_networkhospitalwherethehospital);
                if (competitorView != null)
                    entity["new_ismedicalcouplet"] = (bool)competitorView.new_iscoopmedicalcouplet;

                if (recommendModel.userid == Guid.Empty)
                {
                    commonWcf.UpdateEntityById(entity);
                }
                else
                {
                    commonWcf.UpdateEntityProxyById(recommendModel.userid, entity);
                }
                resResult = resResult.SuccessResult();
            }
            catch (Exception ex)
            {
                log.Error("RecommendBll对象中，UpdateRecommend方法:" + ex.StackTrace + ex.Message);
                resResult = resResult.FailResult(ex.Message);
            }
            return resResult;
        }
    }
}
